using System.Windows.Input;
using Caliburn.Micro;
using Client.Messages;
using Dto.ApiRequests;
using Dto.ApiResponses;
using Sanelib.Core;
using Sanelib.Dto;
using Sanelib.Net.Http;

namespace ClientUI.ViewModel
{
    public class CardRegViewModel : Screen
    {
        private MemberCardResponse _item;
        public MemberCardResponse Item
        {
            get { return _item; }
            set { _item = value; NotifyOfPropertyChange(() => Item); }
        }

        private string _message;
        public string Message
        {
            get
            {
                return _message;
            }
            set
            {
                _message = value;
                NotifyOfPropertyChange(() => Message);
                Logger.Log(LogType.Info, this, value);
            }
        }

        private string _barcode;
        public string Barcode
        {
            get
            {
                if (_barcode == null) _barcode = string.Empty;
                return _barcode.ToUpper();
            }
            set
            {
                _barcode = value.ToUpper();
                NotifyOfPropertyChange(() => Barcode);
                IsBarcodeFocused = true;
            }
        }

        private bool _force;
        public bool Force
        {
            get
            {
                return _force;
            }
            set
            {
                _force = value; NotifyOfPropertyChange(() => Force);
            }
        }

        private bool _isBarcodeFocused;
        public bool IsBarcodeFocused
        {
            get { return _isBarcodeFocused; }
            set { _isBarcodeFocused = value; NotifyOfPropertyChange(() => IsBarcodeFocused); }
        }

        public void BarcodeKeyDown(KeyEventArgs args)
        {
            if (Barcode.Length == 0) return;
            if (args.Key == Key.Return)
            {
                RegIt();
            }
        }

        private string _memberName;
        public string MemberName
        {
            get
            {
                return _memberName;
            }
            set
            {
                _memberName = value;
                NotifyOfPropertyChange(() => MemberName);
            }
        }

        protected override void OnActivate()
        {
            Message = "Choose your options.";
            base.OnActivate();
            Barcode = string.Empty;
        }

        protected override void OnDeactivate(bool close)
        {
            Clear();
            base.OnDeactivate(close);
        }

        public void Show()
        {
            if (string.IsNullOrEmpty(Barcode))
            {
                Message = "Barcode is missing.";
                return;
            }

            Message = "Showing details for code " + Barcode;

            ErrorResult errors;

            var response = Processor.ExecuteRequest<MemberCardRegisterForm, MemberCardResponse>(ContentType.JSON, RequestType.GET, null, out errors);

            if (!errors.IsValid)
            {
                ShowAndLogMessage("Tracker", errors.ToString());
                return;
            }

            Item = response;
            Barcode = Item.Code;
        }

        public void RegIt()
        {
            Message = "Finding member data for : " + Barcode;

            ErrorResult errors;

            var request = new MemberLookupForm
            {
                Code = Barcode
            };

            var response = Processor.ExecuteRequest<MemberLookupForm, MemberCardResponse>(ContentType.JSON, RequestType.GET, request, out errors);

            if (!errors.IsValid)
            {
                ShowAndLogMessage("Tracker", errors.ToString());
                return;
            }

            Item = response;
            MemberName = Item.Name;

            Message = "Member found. Registering for barcode : " + Barcode;

            var regMember = new MemberCardRegisterForm
            {
                TagId = Barcode,
                Code = Barcode
            };

            var response = Processor.ExecuteRequest<MemberCardRegisterForm, MemberCardResponse>(ContentType.JSON, RequestType.POST, regMember, out errors);

            if (!errors.IsValid)
            {
                ShowAndLogMessage("Tracker", errors.ToString());
                return;
            }

            Item = response;
            MemberName = Item.Name;

            Message = "Member Registered Successfully";
        }
        
        public void Clear()
        {
            Item = null;
            MemberName = string.Empty;
            Message = "Message cleared";
            IsBarcodeFocused = true;
        }

        public void Exit()
        {
            EventAggregatorContainer.EventAggregator.Publish(new ChangeView("TrackerViewModel"));
        }

        #region Logging

        private void ShowAndLogMessage(string key, string message)
        {
            var msg = string.Format("{0} - {1}", key, message);
            Logger.Log(LogType.Info, this, msg);
            _message = msg;
            NotifyOfPropertyChange(() => Message);
        }

        #endregion
    }
}
